using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using APJUtil = APJ.Util;

namespace MTRC.ODMS.Web.SOM.UserControl
{
    /// <summary>
    /// Author:Huangyao
    /// //huangyao 20090122 fixed TD:1156
    /// </summary>
    public partial class UCSignatureDeparture : MTRC.ODMS.Web.UserControl.BaseUserControl
    {
        private string PreviousSignFullFileName
        {
            get
            {
                return string.Concat(this.ViewState["_previousSignFullFileName"]);
            }
            set
            {
                this.ViewState["_previousSignFullFileName"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.PreviousSignFullFileName != this.GetSignatureFullFileName(1))
            {
                this.IsNeedSignAgain = false;
            }

            //------------------------------20090121--------------
            string fullFileName = "";
            fullFileName = string.Concat(Session[MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Departure]);
            if (fullFileName != string.Empty)
            {
                this.hdnSignFileName.Value = fullFileName;
                //prefix: Signature_Handwritten_
                //prefix: Signature_PhotoCapture_
                if (fullFileName.IndexOf("Signature_Handwritten_") > -1)
                {
                    this.hdnSignType.Value = "2";
                }
                else
                {
                    this.hdnSignType.Value = "1";
                }
                Session[MTRC.ODMS.BLL.COM.Session.SOM_SignatureFullFileName_Departure] = null; //set this value to empty//but this has a hidden issue, the better way is use return value from popup form, but ,it can not work now,
                this.SetImgSignatureScript();
            }
            //-------------end-----------------20090121--------------

            this.SetFlagPictureShow();
        }

        private void SetImgSignatureScript()
        {
            string scriptNeedToBind = "";
            string fullFileName = string.Concat(this.hdnSignFileName.Value).Trim();
            if (fullFileName != string.Empty)
            {
                fullFileName = HttpUtility.UrlEncode(fullFileName);
                if (this.GetSignatureType() == 1)
                {
                    //photo
                    scriptNeedToBind = "OpenPhotoCaptureFormDeparture('" + "true" + "', '" + 1.ToString() + "', '" + fullFileName + "', '" + this.ClientID + "'); return false;";
                    this.imgSignature.Attributes.Add("OnClick", scriptNeedToBind);
                }
                else
                {
                    //hand
                    scriptNeedToBind = "OpenHandWrittenFormDeparture('" + "true" + "', '" + 1.ToString() + "', '" + fullFileName + "', '" + this.ClientID + "'); return false;";
                    this.imgSignature.Attributes.Add("OnClick", scriptNeedToBind);
                }
                this.imgSignature.Attributes.Add("style", "cursor:hand;");
                this.imgSignature.ToolTip = this.GetLabel("SOM_SignViewPreviousPic");

                //----------------------
                string findString = "Bottom";
                string controlName = "";
                string controlValue = "";
                //controlName = this.ClientID + @"$hdnSignFileName";
                //controlValue = ( (System.Web.UI.HtmlControls.HtmlInputHidden) this.Parent.FindControl(controlName) ).Value;
                if (this.ClientID.IndexOf(findString) > -1)
                {
                    //set oppsite control value
                    //controlName = this.ClientID.Substring(this.ClientID.IndexOf(findString) ) + @"$hdnSignFileName"; 
                    controlName = this.ClientID.Substring(0, this.ClientID.IndexOf(findString));
                }
                else
                {
                    //controlName = this.ClientID + findString + @"$hdnSignFileName"; 
                    controlName = this.ClientID + findString;
                }
                //((System.Web.UI.HtmlControls.HtmlInputHidden)this.Parent.FindControl(controlName)).Value = controlValue;
                object oppsiteControl = this.Parent.FindControl(controlName);
                if (oppsiteControl != null)
                {
                    UCSignatureDeparture tempUCSignature = (UCSignatureDeparture)this.Parent.FindControl(controlName);
                    if (tempUCSignature.GetSignatureFullFileName(1) != this.hdnSignFileName.Value)
                    {
                        tempUCSignature.InitUCSignatureValue(1, this.GetSignatureType(), this.hdnSignFileName.Value);
                        //tempUCSignature.SetEnable(this.btnPhotoCapture.Enabled, 1);
                        tempUCSignature.IsNeedSignAgain = this.IsNeedSignAgain;
                    }
                }
                //---------end
            }
            else
            {
                this.imgSignature.Attributes.Add("style", "cursor:default;disable");
                this.imgSignature.Attributes.Add("OnClick", ""); //clear the Event
                this.imgSignature.ToolTip = "";
            }
        }

        private void SetFlagPictureShow()
        {
            if (string.Concat(this.hdnSignFileName.Value) == string.Empty) //huangyao 20090122 fixed TD:1156
            {
                this.imgSignature.ImageUrl = "~/Images/SOM/Sign_UnSignature.gif";
            }
            else
            {
                this.imgSignature.ImageUrl = "~/Images/SOM/Sign_Signature.gif";
            }

            //should get from resource.xml
            //this.btnOpenCapture.ToolTip = "Show Book On Signature details panel";
        }

        /// <summary>
        /// Set user control internal language
        /// </summary>
        public void SetLanguage()
        {
            this.lblSignature.Text = this.GetLabel("SOM_Signature_LabelText", true);
            this.btnPhotoCapture.Text = this.GetLabel("SOM_SignType_PhotoCapture"); //huangyao 20090122 fixed TD:1156
            this.btnHandWritten.Text = this.GetLabel("SOM_SignType_HandWritten"); //huangyao 20090122 fixed TD:1156
            this.btnOpenCapture.ToolTip = this.GetLabel("SOM_SignType_OpenCaptureToolTip");
        }

        /// <summary>
        /// Override for HZX-AR page departure signature use
        /// </summary>
        /// <param name="enable">enable or disable</param>
        /// <param name="eventSignType">1. arrival, 2. departure, 2--only for AR use</param>
        /// <param name="hadSigned"> Only for Departure signature use, if had signed, pass true, else false</param>
        public void SetEnable(bool enable, int eventSignType, bool hadSigned)
        {
            eventSignType = 2; //hard code: 2 means: departure

            this.btnPhotoCapture.Enabled = enable; //huangyao 20090122 fixed TD:1156
            this.btnHandWritten.Enabled = enable; //huangyao 20090122 fixed TD:1156
            //this.imgSignature.Visible = enable; //huangyao 20090122 fixed TD:1156

            //can open view sign Picture, but can not sign
            this.btnOpenCapture.Enabled = enable;

            //-----------For departure station use-------
            if (eventSignType == 2 && hadSigned)
            {
                //this.btnOpenCapture.Enabled = true; //huangyao 20090122 fixed TD:1156
            }
            else
            {
                //if in departure sign, when fileName empty, btnOpenCapture can not click, no need set
                //this.btnOpenCapture.Enabled = false;
            }
            //--------------

            //OpenSignatureForm(); return false;
            string isReadOnly = "true";
            if (enable)
            {
                isReadOnly = "false";
            }
            else
            {
                //if read only, no need signature again
                this.IsNeedSignAgain = false;
            }

            string scriptNeedToBind = "";

            //------------------------------20090121--------------
            scriptNeedToBind = "OpenPhotoCaptureFormDeparture('" + isReadOnly + "', '" + eventSignType.ToString() + "', '" + "" + "', '" + this.ClientID + "'); return false;";
            this.btnPhotoCapture.Attributes.Add("OnClick", scriptNeedToBind);

            scriptNeedToBind = "OpenHandWrittenFormDeparture('" + isReadOnly + "', '" + eventSignType.ToString() + "', '" + "" + "', '" + this.ClientID + "'); return false;";
            this.btnHandWritten.Attributes.Add("OnClick", scriptNeedToBind);
            //-------------end-----------------20090121--------------

        }

        /// <summary>
        /// Set some user control internal value
        /// </summary>
        /// <param name="eventSignType">1.AL, FL, AR Event Time, 2. Only for AR depart time</param>
        /// <param name="signType">1--photo capture, 2. handwritting</param>
        /// <param name="signFileName">when had signed , pass signature file name, else empty</param>
        public void InitUCSignatureValue(int eventSignType, int signType, string signFileName)
        {
            this.hdnSignType.Value = signType.ToString(); //huangyao 20090122 fixed TD:1156

            eventSignType = 2; //hard code: 2 means: departure

            this.SetSignatureFullFileName(eventSignType, signFileName);
            this.PreviousSignFullFileName = signFileName;

            this.SetImgSignatureScript(); //huangyao 20090122 fixed TD:1156
        }

        /// <summary>
        /// get signature full file name
        /// </summary>
        /// <param name="eventSignType">1. arrival, 2. departure, 2--only for AR use</param>
        /// <returns></returns>
        public string GetSignatureFullFileName(int eventSignType)
        {
            eventSignType = 2; //hard code: 2 means: departure

            string fullFileName = "";
            if (eventSignType == 1)
            {
                
            }
            else
            {
                fullFileName = this.hdnSignFileName.Value; //huangyao 20090122 fixed TD:1156
            }

            return fullFileName;
        }

        private void SetSignatureFullFileName(int eventSignType, string signatureFullFileName)
        {
            eventSignType = 2; //hard code: 2 means: departure

            if (eventSignType == 1)
            {
                
            }
            else
            {
                this.hdnSignFileName.Value = signatureFullFileName; //huangyao 20090122 fixed TD:1156
            }
        }

        /// <summary>
        /// Retrieve signature type
        /// 1. means Photo capture
        /// 2. means Signature painting
        /// </summary>
        /// <returns></returns>
        public int GetSignatureType()
        {
            int signatureType = 1;
            int.TryParse(hdnSignType.Value.Trim(), out signatureType); //huangyao 20090122 fixed TD:1156

            return signatureType;
        }

        /// <summary>
        /// judge need signature again
        /// Just use in AL currently
        /// </summary>
        public bool IsNeedSignAgain
        {
            get
            {
                bool isNeedSignAgain = false;
                bool.TryParse(string.Concat(ViewState[MTRC.ODMS.BLL.COM.Session.SOM_IsNeedSignAgain]), out isNeedSignAgain);
                return isNeedSignAgain;
            }
            set
            {
                ViewState[MTRC.ODMS.BLL.COM.Session.SOM_IsNeedSignAgain] = value;
            }
        }

        protected void hdnForRefresh_ServerChange(object sender, EventArgs e)
        {
            string ss = "";
        }

        //------20081013 night---
        /// <summary>
        /// Move temp signature picture file to real path
        /// </summary>
        public void SaveTempFileToRealPath()
        {
            string fileName = this.GetSignatureFullFileName(1);
            string realPath = APJ.Util.Utility.GetAppSetting("SOM_SignatureFilePath");
            string tempPath = APJ.Util.Utility.GetAppSetting("SOM_SignatureFileTempPath");
            //remove to real path
            //SOM_SignatureFilePath
            //string fullFileName = APJ.Util.Utility.GetAppSetting("SOM_SignatureFileTempPath") + "Signature_PhotoCapture_" + Guid.NewGuid().ToString() + ".gif";
            if (fileName.IndexOf(realPath) == -1)
            {
                //if the signature full file name do not contains Real Path, it means it a temp signature picture
                fileName = APJUtil.Utility.ConvertFromBase64(fileName);
                if (File.Exists(fileName))
                {
                    string newFileName = "";
                    if (this.GetSignatureType() == 1)
                    {
                        newFileName = realPath + "Signature_PhotoCapture_" + Guid.NewGuid().ToString() + ".gif";
                    }
                    else
                    {
                        newFileName = realPath + "Signature_Handwritten_" + Guid.NewGuid().ToString() + ".gif";
                    }
                    //remove
                    File.Move(fileName, newFileName);
                    //this.PreviousSignFullFileName //must delete previous file
                    if (File.Exists(this.PreviousSignFullFileName))
                    {
                        File.Delete(this.PreviousSignFullFileName);
                    }
                    this.SetSignatureFullFileName(2, newFileName);
                }
                else
                {
                    throw new Exception("Can not find the signature file, you should signature again!");
                }

            }
        }
    }
}